/*
 * StruggleChessView.java
 */
package strugglechess;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import sun.audio.*;
import java.io.*;

/**
 * The application's main frame.
 */
// TODO this class is too dense. Dispatch te code in several dedicated classes
public class StruggleChessView extends FrameView {

    // top-left corner of the vitual board
    private int x1;
    private int y1;
    // top-right corner of the vitual board
    private int x2;
    private int y2;
    // bottom-left corner of the vitual board
    private int x3;
    private int y3;
    // bottom-right corner of the vitual board
    private int x4;
    private int y4;

    // White pieces
    final int WP = 1;
    final int WN = 2;
    final int WB = 3;
    final int WR = 4;
    final int WQ = 5;
    final int WK = 6;
    // Black pieces
    final int BP = 7;
    final int BN = 8;
    final int BB = 9;
    final int BR = 10;
    final int BQ = 11;
    final int BK = 12;
    
    Position currentPosition = new Position();
    private Engine engine = new Engine();
    MidiPlayer midiPlayer = new MidiPlayer();

    public StruggleChessView(SingleFrameApplication app) {
        super(app);

        initComponents();
        setBoardDimension(canvas);
        loadImages();
        loadSounds();
        loadMusic();
        playMusic();



        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    int getCornerXfromCR(int C, int R) {
        double cornerY = getCornerYfromCR(C, R);
        double Xmin = (((double) x3 - (double) x1) / ((double) y3 - (double) y1)) * ((double) cornerY - (double) y1) + x1;
        double Xmax = (((double) x4 - (double) x2) / ((double) y4 - (double) y2)) * ((double) cornerY - (double) y2) + x2;
        double cornerX = ((double) C - 1.0) * (((double) Xmax - (double) Xmin) / 8.0) + Xmin;

        return (int) cornerX;
    }

    int getCornerYfromCR(int C, int R) {
        double cornerY = (double) y3 - ((double) R - 1.0) * (((double) y3 - (double) y1) / 8.0);

        // TODO implement the formula if the chessboard is switched
        //double cornerY = (double)y1 + ((double)R -1.0)*(((double)y3-(double)y1)/8.0)  ;
        return (int) cornerY;
    }

    /**
     * Get the X location of the center of the given square on he screen
     *
     * @param C column
     * @param R row
     * @return X
     */
    int getCenterXfromCR(int C, int R) {
        double cornerY = getCornerYfromCR(C, R);
        double Xmin = (((double) x3 - (double) x1) / ((double) y3 - (double) y1)) * ((double) cornerY - (double) y1) + x1;
        double Xmax = (((double) x4 - (double) x2) / ((double) y4 - (double) y2)) * ((double) cornerY - (double) y2) + x2;


        double cornerX = ((double) C - 0.5) * (((double) Xmax - (double) Xmin) / 8.0) + Xmin;

        return (int) cornerX;
    }

    /**
     * Get the Y location of the center of the given square on he screen
     *
     * @param C column
     * @param R row
     * @return Y
     */
    int getCenterYfromCR(int C, int R) {
        double cornerY = (double) y3 - ((double) R - 0.5) * (((double) y3 - (double) y1) / 8.0);

        // TODO implement the formula if the chessboard is switched
        //double cornerY = (double)y1 + ((double)R -1.0)*(((double)y3-(double)y1)/8.0)  ;
        return (int) cornerY;
    }

    /**
     * Get the column on the board from a location on he screen
     *
     * @param X X location on the screen
     * @param Y Y location on the screen
     * @return the column
     */
    int getColFromXY(int X, int Y) {
        double Xmin = (((double) (x3 - x1) / (double) (y3 - y1)) * (double) (Y - y3) + x3);
        double Xmax = (((double) (x4 - x2) / (double) (y4 - y2)) * (double) (Y - y4) + x4);
        int col = (int) (9.0 - ((Xmax - X) / (Xmax - Xmin)) * 8.0);
        return col;
    }

    /**
     * Get the row on the board from a location on he screen
     *
     * @param X X location on the screen
     * @param Y Y location on the screen
     * @return the row
     */
    int getRowFromXY(int X, int Y) {
        //double Xmin = ((double) (x3 - x1) / (double) (y3 - y1)) * (double) (Y - y3) + x3;
        //double Xmax = ((double) (x4 - x2) / (double) (y4 - y2)) * (double) (Y - y4) + x4;
        int row = (int) (((double) (y3 - Y) / (double) (y3 - y1)) * 8.0 + 1.0);
        return row;
    }

    /*
     * Paint the piece present on the given square (col,row)
     *
     * @param graphics the graphics to use for the display
     * @param status status of the piece
     * @param col colomn to display the piece
     * @param row row to display the piece
     *
     */
    public void paintPiece(int pieceCode, int status, int col, int row) {

        // center of the square to display
        int x = getCenterXfromCR(col, row);
        int y = getCenterYfromCR(col, row);


        // TODO change the size of the piece depending on the row
        //int width = (int) (((double) (x2 - x1) / 8.0));
        //int height = y1;

        BufferedImage img1 = null;
        try {
            String filename = "";

            filename += System.getProperty("user.dir");
            //filename += "NetBeansProjects/StruggleChess/";
            filename += "/images/set/";

            String[] piecesNames = {"WP", "WN", "WB", "WR", "WQ", "WK", "BP", "BN", "BB", "BR", "BQ", "BK"};

            //filename += piecesNames[pieceCode-1] + pieceStatus + ".bmp";
            filename += piecesNames[pieceCode - 1];
            filename += status + ".gif";
            img1 = ImageIO.read(new File(filename));

        } catch (IOException e) {
            this.statusMessageLabel.setText("ERROR: image loading failed");
        }

        double scale = getScale();
        int width = (int) (scale * img1.getWidth());
        int height = (int) (scale * img1.getHeight());

        // top-left corner to display the image
        // we must add 1/6 of the height of a square to display the piece at the center
        int xx = (int) ((double) x - ((double) width) / 2.0);
        int yy = (int) ((double) y - ((double) height) + 0.16666 * (y3 - y1) / 8.0);

        Image scaledImg1 = img1.getScaledInstance(width, height, Image.SCALE_SMOOTH);

        canvas.getGraphics().drawImage(scaledImg1, xx, yy, null);
    }

    /*
     * Paint the pieces all the pieces on the board
     *
     * @param graphics the graphics to use for the display
     * 
     */
    public void paintPieces(Graphics graphics) {

        int pieceCode;
        int EMPTY = 0;
        // Draw from the last to the first row
        // TODO switch the order of display when the board is switched
        for (int col = 1; col < 9; col++) {
            for (int row = 8; row > 0; row--) {
                pieceCode = currentPosition.getPiece(col, row);
                if (pieceCode != EMPTY) {
                    paintPiece(pieceCode, 1, col, row);
                }
            }
        }

    }

    /**
     * Paint an empty board
     *
     * @param graphics the graphics to use for the display
     *
     **/
    public void paintBoard(Graphics graphics) {

        int[] xPoints = new int[4];
        int[] yPoints = new int[4];
        int i, j;
        String[] colName = {"a", "b", "c", "d", "e", "f", "g", "h"};

        for (i = 1; i < 9; i++) {
            for (j = 1; j < 9; j++) {
                int nPoints = 0;
                xPoints[nPoints++] = getCornerXfromCR(i, j);
                xPoints[nPoints++] = getCornerXfromCR(i + 1, j);
                xPoints[nPoints++] = getCornerXfromCR(i + 1, j+1);
                xPoints[nPoints++] = getCornerXfromCR(i, j + 1);
                nPoints = 0;
                yPoints[nPoints++] = getCornerYfromCR(i, j);
                yPoints[nPoints++] = getCornerYfromCR(i + 1, j);
                yPoints[nPoints++] = getCornerYfromCR(i + 1, j + 1);
                yPoints[nPoints++] = getCornerYfromCR(i, j + 1);

                int modval = (i + j) % 2;
                if (modval != 0) {
                    graphics.setColor(Color.DARK_GRAY);
                } else {
                    graphics.setColor(Color.lightGray);
                }

                graphics.fillPolygon(xPoints, yPoints, nPoints);

                graphics.setColor(Color.blue);
                graphics.drawString(colName[i - 1] + "" + j, xPoints[0], yPoints[0]);

            }
        }


    }

    public void paintComponent(Canvas canvas, Graphics graphics) {

        graphics.setColor(Color.black);
        graphics.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());

        int SP1 = 10;
        int SP2 = 0;
        int H1 = 20;
        int H2 = 100;


        x1 = canvas.getWidth() * SP1 / 100;
        y1 = canvas.getHeight() * H1 / 100;
        x2 = canvas.getWidth() * (100 - SP1) / 100;
        y2 = y1;
        x3 = canvas.getWidth() * SP2 / 100;
        y3 = canvas.getHeight() * H2 / 100;
        x4 = canvas.getWidth() * (100 - SP2) / 100;
        y4 = y3;

        paintBoard(graphics);
        paintActiveSquares(graphics);
        paintPieces(graphics);


    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = StruggleChessApp.getApplication().getMainFrame();
            aboutBox = new StruggleChessAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        StruggleChessApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        canvas = new java.awt.Canvas();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        newgameMenuItem = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        moveMenu = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem7 = new javax.swing.JMenuItem();
        jMenuItem8 = new javax.swing.JMenuItem();
        optionMenu = new javax.swing.JMenu();
        jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem2 = new javax.swing.JCheckBoxMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        jCheckBoxMenuItem3 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem4 = new javax.swing.JCheckBoxMenuItem();
        jSeparator4 = new javax.swing.JPopupMenu.Separator();
        jCheckBoxMenuItem5 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem6 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem7 = new javax.swing.JCheckBoxMenuItem();
        jSeparator5 = new javax.swing.JPopupMenu.Separator();
        jCheckBoxMenuItem8 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem9 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem10 = new javax.swing.JCheckBoxMenuItem();
        jSeparator6 = new javax.swing.JPopupMenu.Separator();
        jMenu1 = new javax.swing.JMenu();
        levelMenu = new javax.swing.JMenu();
        jCheckBoxMenuItem11 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem12 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem13 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem14 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem15 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem16 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem17 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem18 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem19 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem20 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem21 = new javax.swing.JCheckBoxMenuItem();
        musicMenu = new javax.swing.JMenu();
        playMusicMenuItem = new javax.swing.JMenuItem();
        stopMusicMenuItem = new javax.swing.JMenuItem();
        jSeparator7 = new javax.swing.JPopupMenu.Separator();
        previousTrackMenuItem = new javax.swing.JMenuItem();
        nextTrackMenuItem = new javax.swing.JMenuItem();
        jSeparator8 = new javax.swing.JPopupMenu.Separator();
        randomMusicCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(strugglechess.StruggleChessApp.class).getContext().getResourceMap(StruggleChessView.class);
        mainPanel.setBackground(resourceMap.getColor("mainPanel.background")); // NOI18N
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setPreferredSize(new java.awt.Dimension(640, 480));
        mainPanel.setLayout(new java.awt.BorderLayout());

        canvas.setBackground(resourceMap.getColor("canvas.background")); // NOI18N
        canvas.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        canvas.setName("canvas"); // NOI18N
        canvas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                canvasMouseClicked(evt);
            }
        });
        mainPanel.add(canvas, java.awt.BorderLayout.CENTER);

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(strugglechess.StruggleChessApp.class).getContext().getActionMap(StruggleChessView.class, this);
        newgameMenuItem.setAction(actionMap.get("startNewGame")); // NOI18N
        newgameMenuItem.setText(resourceMap.getString("newgamejMenuItem.text")); // NOI18N
        newgameMenuItem.setName("newgamejMenuItem"); // NOI18N
        fileMenu.add(newgameMenuItem);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setEnabled(false);
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setEnabled(false);
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        fileMenu.add(jMenuItem2);

        jSeparator1.setName("jSeparator1"); // NOI18N
        fileMenu.add(jSeparator1);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        moveMenu.setText(resourceMap.getString("moveMenu.text")); // NOI18N
        moveMenu.setName("moveMenu"); // NOI18N

        jMenuItem4.setText(resourceMap.getString("jMenuItem4.text")); // NOI18N
        jMenuItem4.setEnabled(false);
        jMenuItem4.setName("jMenuItem4"); // NOI18N
        moveMenu.add(jMenuItem4);

        jSeparator2.setName("jSeparator2"); // NOI18N
        moveMenu.add(jSeparator2);

        jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem5.setText(resourceMap.getString("jMenuItem5.text")); // NOI18N
        jMenuItem5.setEnabled(false);
        jMenuItem5.setName("jMenuItem5"); // NOI18N
        moveMenu.add(jMenuItem5);

        jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem6.setText(resourceMap.getString("jMenuItem6.text")); // NOI18N
        jMenuItem6.setEnabled(false);
        jMenuItem6.setName("jMenuItem6"); // NOI18N
        moveMenu.add(jMenuItem6);

        jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem7.setText(resourceMap.getString("jMenuItem7.text")); // NOI18N
        jMenuItem7.setEnabled(false);
        jMenuItem7.setName("jMenuItem7"); // NOI18N
        moveMenu.add(jMenuItem7);

        jMenuItem8.setText(resourceMap.getString("jMenuItem8.text")); // NOI18N
        jMenuItem8.setEnabled(false);
        jMenuItem8.setName("jMenuItem8"); // NOI18N
        moveMenu.add(jMenuItem8);

        menuBar.add(moveMenu);

        optionMenu.setText(resourceMap.getString("optionMenu.text")); // NOI18N
        optionMenu.setName("optionMenu"); // NOI18N

        jCheckBoxMenuItem1.setSelected(true);
        jCheckBoxMenuItem1.setText(resourceMap.getString("jCheckBoxMenuItem1.text")); // NOI18N
        jCheckBoxMenuItem1.setEnabled(false);
        jCheckBoxMenuItem1.setName("jCheckBoxMenuItem1"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem1);

        jCheckBoxMenuItem2.setSelected(true);
        jCheckBoxMenuItem2.setText(resourceMap.getString("jCheckBoxMenuItem2.text")); // NOI18N
        jCheckBoxMenuItem2.setEnabled(false);
        jCheckBoxMenuItem2.setName("jCheckBoxMenuItem2"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem2);

        jSeparator3.setName("jSeparator3"); // NOI18N
        optionMenu.add(jSeparator3);

        jCheckBoxMenuItem3.setSelected(true);
        jCheckBoxMenuItem3.setText(resourceMap.getString("jCheckBoxMenuItem3.text")); // NOI18N
        jCheckBoxMenuItem3.setEnabled(false);
        jCheckBoxMenuItem3.setName("jCheckBoxMenuItem3"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem3);

        jCheckBoxMenuItem4.setSelected(true);
        jCheckBoxMenuItem4.setText(resourceMap.getString("jCheckBoxMenuItem4.text")); // NOI18N
        jCheckBoxMenuItem4.setEnabled(false);
        jCheckBoxMenuItem4.setName("jCheckBoxMenuItem4"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem4);

        jSeparator4.setName("jSeparator4"); // NOI18N
        optionMenu.add(jSeparator4);

        jCheckBoxMenuItem5.setSelected(true);
        jCheckBoxMenuItem5.setText(resourceMap.getString("jCheckBoxMenuItem5.text")); // NOI18N
        jCheckBoxMenuItem5.setEnabled(false);
        jCheckBoxMenuItem5.setName("jCheckBoxMenuItem5"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem5);

        jCheckBoxMenuItem6.setSelected(true);
        jCheckBoxMenuItem6.setText(resourceMap.getString("jCheckBoxMenuItem6.text")); // NOI18N
        jCheckBoxMenuItem6.setEnabled(false);
        jCheckBoxMenuItem6.setName("jCheckBoxMenuItem6"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem6);

        jCheckBoxMenuItem7.setSelected(true);
        jCheckBoxMenuItem7.setText(resourceMap.getString("jCheckBoxMenuItem7.text")); // NOI18N
        jCheckBoxMenuItem7.setEnabled(false);
        jCheckBoxMenuItem7.setName("jCheckBoxMenuItem7"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem7);

        jSeparator5.setName("jSeparator5"); // NOI18N
        optionMenu.add(jSeparator5);

        jCheckBoxMenuItem8.setSelected(true);
        jCheckBoxMenuItem8.setText(resourceMap.getString("jCheckBoxMenuItem8.text")); // NOI18N
        jCheckBoxMenuItem8.setEnabled(false);
        jCheckBoxMenuItem8.setName("jCheckBoxMenuItem8"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem8);

        jCheckBoxMenuItem9.setSelected(true);
        jCheckBoxMenuItem9.setText(resourceMap.getString("jCheckBoxMenuItem9.text")); // NOI18N
        jCheckBoxMenuItem9.setEnabled(false);
        jCheckBoxMenuItem9.setName("jCheckBoxMenuItem9"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem9);

        jCheckBoxMenuItem10.setSelected(true);
        jCheckBoxMenuItem10.setText(resourceMap.getString("jCheckBoxMenuItem10.text")); // NOI18N
        jCheckBoxMenuItem10.setEnabled(false);
        jCheckBoxMenuItem10.setName("jCheckBoxMenuItem10"); // NOI18N
        optionMenu.add(jCheckBoxMenuItem10);

        jSeparator6.setName("jSeparator6"); // NOI18N
        optionMenu.add(jSeparator6);

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setEnabled(false);
        jMenu1.setName("jMenu1"); // NOI18N
        optionMenu.add(jMenu1);

        menuBar.add(optionMenu);

        levelMenu.setText(resourceMap.getString("levelMenu.text")); // NOI18N
        levelMenu.setName("levelMenu"); // NOI18N

        jCheckBoxMenuItem11.setSelected(true);
        jCheckBoxMenuItem11.setText(resourceMap.getString("jCheckBoxMenuItem11.text")); // NOI18N
        jCheckBoxMenuItem11.setName("jCheckBoxMenuItem11"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem11);

        jCheckBoxMenuItem12.setSelected(true);
        jCheckBoxMenuItem12.setText(resourceMap.getString("jCheckBoxMenuItem12.text")); // NOI18N
        jCheckBoxMenuItem12.setName("jCheckBoxMenuItem12"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem12);

        jCheckBoxMenuItem13.setSelected(true);
        jCheckBoxMenuItem13.setText(resourceMap.getString("jCheckBoxMenuItem13.text")); // NOI18N
        jCheckBoxMenuItem13.setName("jCheckBoxMenuItem13"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem13);

        jCheckBoxMenuItem14.setSelected(true);
        jCheckBoxMenuItem14.setText(resourceMap.getString("jCheckBoxMenuItem14.text")); // NOI18N
        jCheckBoxMenuItem14.setName("jCheckBoxMenuItem14"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem14);

        jCheckBoxMenuItem15.setSelected(true);
        jCheckBoxMenuItem15.setText(resourceMap.getString("jCheckBoxMenuItem15.text")); // NOI18N
        jCheckBoxMenuItem15.setName("jCheckBoxMenuItem15"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem15);

        jCheckBoxMenuItem16.setSelected(true);
        jCheckBoxMenuItem16.setText(resourceMap.getString("jCheckBoxMenuItem16.text")); // NOI18N
        jCheckBoxMenuItem16.setName("jCheckBoxMenuItem16"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem16);

        jCheckBoxMenuItem17.setSelected(true);
        jCheckBoxMenuItem17.setText(resourceMap.getString("jCheckBoxMenuItem17.text")); // NOI18N
        jCheckBoxMenuItem17.setName("jCheckBoxMenuItem17"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem17);

        jCheckBoxMenuItem18.setSelected(true);
        jCheckBoxMenuItem18.setText(resourceMap.getString("jCheckBoxMenuItem18.text")); // NOI18N
        jCheckBoxMenuItem18.setName("jCheckBoxMenuItem18"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem18);

        jCheckBoxMenuItem19.setSelected(true);
        jCheckBoxMenuItem19.setText(resourceMap.getString("jCheckBoxMenuItem19.text")); // NOI18N
        jCheckBoxMenuItem19.setName("jCheckBoxMenuItem19"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem19);

        jCheckBoxMenuItem20.setSelected(true);
        jCheckBoxMenuItem20.setText(resourceMap.getString("jCheckBoxMenuItem20.text")); // NOI18N
        jCheckBoxMenuItem20.setName("jCheckBoxMenuItem20"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem20);

        jCheckBoxMenuItem21.setSelected(true);
        jCheckBoxMenuItem21.setText(resourceMap.getString("jCheckBoxMenuItem21.text")); // NOI18N
        jCheckBoxMenuItem21.setName("jCheckBoxMenuItem21"); // NOI18N
        levelMenu.add(jCheckBoxMenuItem21);

        menuBar.add(levelMenu);

        musicMenu.setText(resourceMap.getString("musicMenu.text")); // NOI18N
        musicMenu.setName("musicMenu"); // NOI18N

        playMusicMenuItem.setAction(actionMap.get("playMusic")); // NOI18N
        playMusicMenuItem.setText(resourceMap.getString("playMusicMenuItem.text")); // NOI18N
        playMusicMenuItem.setName("playMusicMenuItem"); // NOI18N
        musicMenu.add(playMusicMenuItem);

        stopMusicMenuItem.setAction(actionMap.get("stopMusic")); // NOI18N
        stopMusicMenuItem.setText(resourceMap.getString("stopMusicMenuItem.text")); // NOI18N
        stopMusicMenuItem.setName("stopMusicMenuItem"); // NOI18N
        musicMenu.add(stopMusicMenuItem);

        jSeparator7.setName("jSeparator7"); // NOI18N
        musicMenu.add(jSeparator7);

        previousTrackMenuItem.setAction(actionMap.get("previousTrack")); // NOI18N
        previousTrackMenuItem.setText(resourceMap.getString("previousTrackMenuItem.text")); // NOI18N
        previousTrackMenuItem.setName("previousTrackMenuItem"); // NOI18N
        musicMenu.add(previousTrackMenuItem);

        nextTrackMenuItem.setAction(actionMap.get("nextTrack")); // NOI18N
        nextTrackMenuItem.setText(resourceMap.getString("nextTrackMenuItem.text")); // NOI18N
        nextTrackMenuItem.setName("nextTrackMenuItem"); // NOI18N
        musicMenu.add(nextTrackMenuItem);

        jSeparator8.setName("jSeparator8"); // NOI18N
        musicMenu.add(jSeparator8);

        randomMusicCheckBoxMenuItem.setAction(actionMap.get("checkRandomPlay")); // NOI18N
        randomMusicCheckBoxMenuItem.setText(resourceMap.getString("randomMusicCheckBoxMenuItem.text")); // NOI18N
        randomMusicCheckBoxMenuItem.setName("randomMusicCheckBoxMenuItem"); // NOI18N
        musicMenu.add(randomMusicCheckBoxMenuItem);

        menuBar.add(musicMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        helpMenu.add(jMenuItem3);

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 266, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
        addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                formPropertyChange(evt);
            }
        });
    }// </editor-fold>//GEN-END:initComponents
    int col1 = 0;
    int row1 = 0;
    int col2 = 0;
    int row2 = 0;

    private void canvasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_canvasMouseClicked

        String message = "";
        statusMessageLabel.setText("");

        //String param = evt.paramString();
        int x = evt.getX();
        int y = evt.getY();
        message += "Click detected :  x=" + x + "  y=" + y;


        int col = getColFromXY(x, y);
        int row = getRowFromXY(x, y);
        
        /*
        // TESTING ENGINE *****************
        Move computerMove = this.engine.getBestMove(currentPosition, 5, Integer.MAX_VALUE);
        col1 = computerMove.col1;
        row1 = computerMove.row1;
        col2 = computerMove.col2;
        row2 = computerMove.row2;
        makeMove(col1, row1, col2, row2);
        // ***************************** END
        */
        
        if (col > 0 && col < 9 && row > 0 && row < 9) {
            String[] cols = {"a", "b", "c", "d", "e", "f", "g", "h"};
            String colLetter = cols[col - 1];
            message += "   Col=" + colLetter + " Row=" + row;
        }

        System.out.println(message);

        // save the square clicked or perform the move
        if (col > 0 && col < 9 && row > 0 && row < 9) {

            if (col1 == 0 || row1 == 0) {
                col1 = col;
                row1 = row;
            } else {
                col2 = col;
                row2 = row;


                if (engine.isPossibleMove(currentPosition, col1, row1, col2, row2)) {
                    makeMove(col1, row1, col2, row2);
                } else {
                    statusMessageLabel.setText("ILLEGAL MOVE");
                }

                col1 = row1 = col2 = row2 = 0;
            }
        }
        


        paintComponent(canvas, canvas.getGraphics());

    }//GEN-LAST:event_canvasMouseClicked

    private void formPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_formPropertyChange
    }//GEN-LAST:event_formPropertyChange
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.awt.Canvas canvas;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem10;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem11;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem12;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem13;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem14;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem15;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem16;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem17;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem18;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem19;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem2;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem20;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem21;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem3;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem4;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem5;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem6;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem7;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem8;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem7;
    private javax.swing.JMenuItem jMenuItem8;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JPopupMenu.Separator jSeparator4;
    private javax.swing.JPopupMenu.Separator jSeparator5;
    private javax.swing.JPopupMenu.Separator jSeparator6;
    private javax.swing.JPopupMenu.Separator jSeparator7;
    private javax.swing.JPopupMenu.Separator jSeparator8;
    private javax.swing.JMenu levelMenu;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenu moveMenu;
    private javax.swing.JMenu musicMenu;
    private javax.swing.JMenuItem newgameMenuItem;
    private javax.swing.JMenuItem nextTrackMenuItem;
    private javax.swing.JMenu optionMenu;
    private javax.swing.JMenuItem playMusicMenuItem;
    private javax.swing.JMenuItem previousTrackMenuItem;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JCheckBoxMenuItem randomMusicCheckBoxMenuItem;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JMenuItem stopMusicMenuItem;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;

    private void setBoardDimension(Canvas canvas) {
        int SP1 = 10;
        int SP2 = 0;
        int H1 = 20;
        int H2 = 100;


        x1 = canvas.getWidth() * SP1 / 100;
        y1 = canvas.getHeight() * H1 / 100;
        x2 = canvas.getWidth() * (100 - SP1) / 100;
        y2 = y1;
        x3 = canvas.getWidth() * SP2 / 100;
        y3 = canvas.getHeight() * H2 / 100;
        x4 = canvas.getWidth() * (100 - SP2) / 100;
        y4 = y3;
    }

    private double min(double d1, double d2) {
        return ((d1 < d2) ? d1 : d2);
    }

    private double getScale() {
        return min((canvas.getWidth() / 640.0), (canvas.getHeight() / 480.0));
    }

    @Action
    public void startNewGame() {
        currentPosition.newGame();
    }

    private void paintActiveSquares(Graphics graphics) {

        if (col1 != 0 && row1 != 0) {

            int[] xPoints = new int[4];
            int[] yPoints = new int[4];
            int i = col1;
            int j = row1;
            int nPoints = 0;
            xPoints[nPoints++] = getCornerXfromCR(i, j);
            xPoints[nPoints++] = getCornerXfromCR(i + 1, j);
            xPoints[nPoints++] = getCornerXfromCR(i + 1, j + 1);
            xPoints[nPoints++] = getCornerXfromCR(i, j + 1);
            nPoints = 0;
            yPoints[nPoints++] = getCornerYfromCR(i, j);
            yPoints[nPoints++] = getCornerYfromCR(i + 1, j);
            yPoints[nPoints++] = getCornerYfromCR(i + 1, j + 1);
            yPoints[nPoints++] = getCornerYfromCR(i, j + 1);


            if (currentPosition.isWhiteToMove()) {
                graphics.setColor(Color.RED);
            } else {
                graphics.setColor(Color.BLUE);
            }
            graphics.drawPolygon(xPoints, yPoints, nPoints);
        }
    }
    private BufferedImage[][] imageSet = null;
    /*
     * Load image set for the game
     */

    public void loadImages() {
        imageSet = new BufferedImage[12][100];

        String[] piecesNames = {"WP", "WN", "WB", "WR", "WQ", "WK", "BP", "BN", "BB", "BR", "BQ", "BK"};

        int counter = 0;

        for (int pieceCode = 1; pieceCode < 13; pieceCode++) {
            String filename = "";
            String filenameI = "";
            filename += System.getProperty("user.dir");
            filename += "/images/set/";
            filename += piecesNames[pieceCode - 1];

            for (int index = 0; index < 100; index++) {
                filenameI = filename + index + ".gif";
                try {
                    imageSet[pieceCode - 1][index] = ImageIO.read(new File(filenameI));
                    counter++;
                } catch (IOException ex) {
                    ex.getMessage();
                }
            }
        }

        System.out.println(counter + " images loaded successfully");
    }
    private FileInputStream[] soundSet = null;
    /*
     * Load soundSet for the game
     */

    public void loadSounds() {

        soundSet = new FileInputStream[21];
        FileInputStream inStream = null;

        //String[] piecesNames = {"WP", "WN", "WB", "WR", "WQ", "WK", "BP", "BN", "BB", "BR", "BQ", "BK"};
        int counter = 0;
        for (int i = 2; i < 21; i++) {
            String filename = "";
            filename += System.getProperty("user.dir");
            filename += "/sound/";
            filename += "track_" + ((i < 10) ? "0" : "") + i + "-20.wav";

            /*
            try {
                inStream = new FileInputStream(filename);
                soundSet[i] = inStream;
            } catch (FileNotFoundException ex) {
                Logger.getLogger(StruggleChessView.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                soundSet[i - 1] = new AudioStream(inStream);
                Logger.getLogger("inStream loaded with success for " + filename);
            } catch (IOException ex) {
                Logger.getLogger(StruggleChessView.class.getName()).log(Level.SEVERE, null, ex);
            }
             
             */
            counter++;

        }
        System.out.println(counter + " sound files loaded with success");
    }

    /*
     * Make the move
     */
    private void makeMove(int col1, int row1, int col2, int row2) {
        // TODO implement animated moves
        // TODO implement animated captures
        int pieceCode = currentPosition.getPiece(col1, row1);
        playPieceMusic(pieceCode);
        currentPosition.move(col1, row1, col2, row2);
    }

    /*
     * Play the sound related to the piece
     */
    private void playPieceMusic(int pieceCode) {

        switch (pieceCode) {
            case WN:
                playSound(8);
                break;
            case BN:
                playSound(9);
                break;
            case WP:
                playSound(12);
                break;
            case BP:
                playSound(13);
                break;
            case WQ:
                playSound(14);
                break;
            case BQ:
                playSound(15);
                break;
            case WK:
                playSound(10);
                break;
            case BK:
                playSound(11);
                break;
            case WB:
                playSound(16);
                break;
            case BB:
                playSound(17);
                break;
            case WR:
                playSound(18);
                break;
            case BR:
                playSound(19);
                break;
            default:
                break;
        }

    }

    /*
     * play the sound
     */
    private void playSound(int index) {
        // TODO find out how to play the sounds and musics correctly
        /*

        AudioStream sound = null;
        try {
        // TODO implement the playback of sounds
        sound = new AudioStream(soundSet[index]);

        } catch (IOException ex) {
        Logger.getLogger(StruggleChessView.class.getName()).log(Level.SEVERE, null, ex);
        }

        AudioPlayer.player.start(sound);
         */
    }

    /**
     * Load the music into the playlist
     */
    private void loadMusic() {
        String path = System.getProperty("user.dir");
        path += "/music/";
        midiPlayer.loadPlaylist(path);
    }

    
    @Action
    public void playMusic() {
        midiPlayer.play();
    }

    @Action
    public void stopMusic() {
        midiPlayer.stop();
    }

    @Action
    public void previousTrack() {
        midiPlayer.previous();
    }

    @Action
    public void nextTrack() {
        midiPlayer.next();
    }

    @Action
    public void checkRandomPlay() {
        midiPlayer.setRandom(randomMusicCheckBoxMenuItem.isSelected());
    }
}
